package service

import (
	"database-platform/dal/db"
	"database-platform/logger"
	"database-platform/model"
	"fmt"
)

// GetDatabaseList 获取数据库列表
func GetDatabaseList(params *model.DatabaseListRequest) (*model.DatabaseListResponse, error) {
	var response = &model.DatabaseListResponse{}

	var request = &model.Database{
		DBType:       params.DBType,
		PhysicalName: params.PhysicalName,
		LogicalName:  params.LogicalName,
		ClusterID:    params.ClusterID,
		Env:          params.Env,
		IsShard:      params.IsShard,
		AppName:      params.AppName,
		BusinessOne:  params.BusinessOne,
		BusinessTwo:  params.BusinessTwo,
		Status:       params.Status,
	}

	result, count, err := db.ListDatabaseRecords(request, params.Page, params.PageSize, params.Search, params.ShowCluster)
	if err != nil {
		return nil, err
	}
	msg := fmt.Sprintf("[service.GetDatabaseList], result: %v, count:%d, request: %v", result, count, request)
	logger.Logger.Warn(msg)

	response.Count = count
	response.Records = result
	response.Page = params.Page
	response.PageSize = params.PageSize

	return response, nil
}

func GetDatabaseById(id int) (*model.Database, error) {
	result, err := db.GetDatabaseRecordById(id)
	if err != nil {
		return nil, err
	}
	msg := fmt.Sprintf("[service.GetDatabaseById], result: %v,  id: %v", result, id)
	logger.Logger.Warn(msg)

	return result, nil
}

// InsertDatabase 插入数据库记录
func InsertDatabase(database *model.Database) error {
	err := db.InsertDatabaseRecord(database)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.InsertDatabase],  database: %v", database)
	logger.Logger.Warn(msg)

	return nil
}

// UpdateDatabase 更新数据库记录
func UpdateDatabase(id int, database *model.Database) error {
	err := db.UpdateDatabaseRecord(id, database)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.UpdateDatabase],  database: %v", database)
	logger.Logger.Warn(msg)

	return nil
}

// DeleteDatabase 删除数据库记录
func DeleteDatabase(id int) error {
	err := db.DeleteDatabaseRecord(id)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.DeleteDatabase],  id: %v", id)
	logger.Logger.Warn(msg)

	return nil
}
